var MY_CLINIC_INFO = (function() {

	/**
	 * 查询所有机构
	 * */
	function loadInstitutions(){
		
		var params = {};
		
		var institutionName = $.trim($('#institutionName').val());
		if ( institutionName.length ){
			params.institutionName = institutionName;
		}
		// var underInvs = $('input[name="underInvs"]:checked').val();
		var underInvs = $('select[name="underInvs"]').val();
		params.underInvs = underInvs;//是否上线
		var prescriptionInvs = $('select[name="prescriptionInvs"]').val();
		params.prescriptionInvs = prescriptionInvs;//是否处方监管
		var occupationalLicenceStatus = $('select[name="occupationalLicenceStatus"]').val();
		params.occupationalLicenceStatus = occupationalLicenceStatus;//执照知否过期
        var institutionTypeFirst = $('select[name="institutionTypeFirstScreen"]').val();
        params.institutionTypeFirst = institutionTypeFirst;//医疗机构类别

		
		var $tbodyInstitutionList = $('#tbodyInstitutionList');
		$tbodyInstitutionList.empty();
		
		WeKnow.loading();
		
		$.ajax({ 
	        type: "POST", 
	        url: "invs_clinic_info.do/load", 
	        dataType: "json",
	        data: params,
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		// 把取到的结果放到
	        		var e = '';
	        		
	        		if ( 'datalist' in data && data.datalist.length == 0 ){
	        				e +='<tr><td class="text-left bg-warning" colspan=9>未查询到医疗机构数据</td></tr>';
	        		} else {
	        			$(data.datalist).each(function( idx,_a){
		        			e+='<tr ';
		        					e+= ( _a.underInvs == 1?' class="pointer" ':' class="pointer bg-warning" ');
			        				e+= ' data-institution_id="' + _a.id + '"';
			        				e+= ' data-institution_name="' + _a.name + '"';
									e+= ' data-institution_type="' + _a.institutionType + '"';
									e+= ' data-institution_type_first="' + _a.institutionTypeFirst + '"';
									e+= ' data-institution_type_second="' + _a.institutionTypeSecond + '"';
									e+= ' data-institution_attr="' + _a.institutionAttr + '"';
                                    e+= ' data-town="' + _a.town + '"';
		        			e+='>';
	        					// 诊所名
		        				e+='<td class="text-left">'+  _a.name + '</td>';
		        				// 鉴管系统是否已经导入
		        				e+='<td class="text-center">'+ ( _a.underInvs == 1 ?'监管中':'<font style="color:red;">未监管</font></td>') ;
								e+='<td class="text-center">'+ ( _a.prescriptionInvs == 1 ?'监管中':'<font style="color:red;">未监管</font></td>') ;
								e+='<td class="text-center">';
								if(_a.institutionAttr == "0"){
									e+='公立</td>';
								}else if(_a.institutionAttr == "1"){
									e+='民营</td>';
								}else{
									e+='<font style="color:red;">未设置</font></td>';
								}
		        				//所属机构类型
								e+='<td class="text-left">'+ (_a.institutionTypeFirstName==null?'<font style="color:red;">未归类</font>':_a.institutionTypeFirstName) + '</td>';
								e+='<td class="text-left">'+ (_a.institutionTypeSecondName==null?'<font style="color:red;">未归类</font>':_a.institutionTypeSecondName) + '</td>';
		        				// 诊所地址
		        				e+='<td class="text-left">'+ (_a.address==null?'':_a.address) + '</td>';
		        				// 负责人
		        				e+='<td class="text-left">'+ ( _a.ownerName == null?'':_a.ownerName) + '</td>';
		        				// 联系电话
		        				e+='<td class="text-left">'+ (_a.tel==null?'':_a.tel) + '</td>';
		        				// 医生人数
		        				e+='<td class="text-right">'+ (_a.doctorCnt==null?'0':_a.doctorCnt) + '</td>';
		        				// 医生名字
		        				e+='<td class="text-left">'+ (_a.doctorNames==null?'':(_a.doctorNames.length>30?_a.doctorNames.substring(0,30)+"......":_a.doctorNames)) + '</td>';
		        				// 营业执照
		        				if ( _a.businessLicence == null ){
		        					e+='<td class="text-center"></td>';
		        				} else {
		        					e+='<td class="text-center" data-type="business_licence">' +
										'<button type="button" name="showImage" class="btn btn-primary btn-xs illegal-btn">查看</button>' +
										'<button type="button" name="download"style="margin-left: 5px;" class="btn btn-primary btn-xs illegal-btn">下载</button>' +
										// '<button type="button" name="edit" style="margin-left: 5px;" class="btn btn-primary btn-xs illegal-btn">修改</button>' +
										'</td>';
		        				}
								// 执业范围
								e+='<td class="text-left">'+ (_a.technicalOfficesNames==null?'':_a.technicalOfficesNames) + '</td>';
		        				// 执照过期日
								e+='<td class="text-left">'+ ( _a.occupationalLicenceEndDate == null?'暂无执照过期时间': new Date(_a.occupationalLicenceEndDate).format('yyyy-MM-dd') )+'</td>';
		        				// 执业许可证
		        				if ( _a.occupationalLicence == null ){
		        					e+='<td class="text-center"></td>';		
		        				} else {
		        					e+='<td class="text-center" data-type="occupational_licence">' +
										'<button type="button" name="showImage" class="btn btn-primary btn-xs illegal-btn">查看</button>' +
										'<button type="button" name="download"style="margin-left: 5px;" class="btn btn-primary btn-xs illegal-btn">下载</button>' +
										// '<button type="button" name="edit"style="margin-left: 5px;" class="btn btn-primary btn-xs illegal-btn">修改</button>' +
										'</td>';
		        				}
		        				// 相关记录
		        				e+='<td class="text-center dropdown">';
			        				e += '<div class="dropdown">';
			        					e += '<button class="btn btn-default dropdown-toggle" type="button" id="' + _a.id + '" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">';
			        						e += '操作<span class="caret"></span>';
			        					e += '</button>';
			        					e += '<ul class="dropdown-menu dropdown-menu-right" aria-labelledby="' + _a.id 
			        						e += '" data-institution_id="' + _a.id + '"';
			        					e += ' >';
			        						e += '<li><a href="javascript:void(0);" name="archival">医生信息</a></li>';
			        						e += '<li><a href="javascript:void(0);" name="invs_set">监管规则</a></li>';
			        						
			        						if ( _a.underInvs == 1 ){
			        							e += '<li><a href="javascript:void(0);" name="closeSupervise">关闭监管</a></li>';
				        					} else {
				        						e += '<li><a href="javascript:void(0);" name="openSupervise">打开监管</a></li>';
				        					}
											if ( _a.prescriptionInvs == 1 ){
												e += '<li><a href="javascript:void(0);" name="closePrescriptionSupervise">关闭处方监管</a></li>';
											} else {
												e += '<li><a href="javascript:void(0);" name="openPrescriptionSupervise">打开处方监管</a></li>';
											}
											// e += '<li><a href="javascript:void(0);" name="institution_type">机构类型</a></li>';
											e += '<li><a href="javascript:void(0);" name="institution_type_link">机构信息修改</a></li>';
			        					e += '</ul>';
			        				e += '</div>';
			        			e+='</td>';
		        			e+='</tr>';
		        		});
	        		}
	        		
	        		$tbodyInstitutionList.append(e);
	        		
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查询失败，请重新登录后再试');
	        	}
	        }
		});
	}
	
	
	/**
	 * 查询单个机构卫监监管配置历史
	 * */
	function loadInstitutionRegisterSetInfo( institutionId ){
		
		var params = {institutionId:institutionId};
		
		var $tbodyRegisterSetInfo = $('#tbodyRegisterSetInfo');
		$tbodyRegisterSetInfo.empty();
		
		var $tbodyRegisterSetHistory = $('#tbodyRegisterSetHistory');
		$tbodyRegisterSetHistory.empty();
		
		WeKnow.loading();
		
		$.ajax({ 
	        type: "POST", 
	        url: "invs_clinic_info.do/load_invs_set_his", 
	        dataType: "json",
	        data: params,
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		// 把取到的结果放到
	        		var e = '';
	        		
	        		if ( 'clinicInfoModel' in data ){
	        			
	        			var NEED = "需要";
	        			var NOT_NEED = "不需要";
	        			
	        			var clinicInfoModel = data.clinicInfoModel;
	        			
	        			e +='<tr>';
	        				// 是否需要器械消毒登记 0:不需要 >0: n天一次
	        				e+='<td class="text-center">'+ ( clinicInfoModel.invsInstrumentSet == 0 ?NOT_NEED:clinicInfoModel.invsInstrumentSet+'天1次' ) + '</td>';
	        				// 是否需要场所空气消毒登记 0:不需要 1:需要
	        				e+='<td class="text-center">'+ ( clinicInfoModel.invsRoomSet == 0 ?NOT_NEED:NEED ) + '</td>';
	        				// 是否需要医废登记 0:不需要 1:需要
	        				e+='<td class="text-center">'+ ( clinicInfoModel.invsWasteSet == 0 ?NOT_NEED:NEED ) + '</td>';
	        				// 是否需要污水余氯日常检测 0:不需要 1:需要
	        				e+='<td class="text-center">'+ ( clinicInfoModel.invsDisinfectantSet == 0 ?NOT_NEED:NEED ) + '</td>';
                           // 是否需要消毒器械检测报告 0:不需要 1:需要
                            e+='<td class="text-center">'+ ( clinicInfoModel.invsInstrumentReportSet == 0 ?NOT_NEED:NEED ) + '</td>';
	        				// 是否需要医废污水检测报告 0:不需要 1:需要
	        				e+='<td class="text-center">'+ ( clinicInfoModel.invsSewageReportSet == 0 ?NOT_NEED:NEED) + '</td>';
	        			e+='</tr>';
	        			$tbodyRegisterSetInfo.append(e);
	        			
	        			var eHis = '';
	        			if ( clinicInfoModel.chiangeHisList && clinicInfoModel.chiangeHisList.length ){
	        				var chiangeHisList = clinicInfoModel.chiangeHisList;
	        				
	        				$(chiangeHisList).each(function(idx,a){
	        					eHis +='<tr>';
		        					eHis+='<td class="text-left">'+ new Date(a.createTm).format('yyyy-MM-dd hh:mm') + '</td>';//变更时间

								    //将配置名转换成中文
									if(a.modifyProperty=="invsInstrumentSet"){
										eHis+='<td class="text-left">器械消毒</td>';//修改的配置名'
									}
									else if(a.modifyProperty=="invsRoomSet"){
										eHis+='<td class="text-left">场所消毒</td>';//修改的配置名'
									}
                                    else if(a.modifyProperty=="invsWasteSet"){
										eHis+='<td class="text-left">医废废物</td>';//修改的配置名'
									}
                                    else if(a.modifyProperty=="invsDisinfectantSet"){
										eHis+='<td class="text-left">余氯日检</td>';//修改的配置名'
									}
                                   else if(a.modifyProperty=="invsSewageReportSet"){
										eHis+='<td class="text-left">污水检测报告</td>';//修改的配置名'
									}
                                    else if(a.modifyProperty=="invsInstrumentReportSet"){
										eHis+='<td class="text-left">消毒器械检测报告</td>';//修改的配置名'
									}else{
                                        eHis+='<td class="text-left">-</td>'
									}

									eHis+='<td class="text-left">'+ ( a.modifyValue == 0?NOT_NEED:NEED ) + '</td>';//修改的配置值
		        					eHis+='<td class="text-left">'+ a.doctorName + '</td>';//操作人
		        					eHis+='<td class="text-left">'+ a.modifyReason + '</td>';//修改理由
	        					eHis +='</tr>';
	        				});
	        			} else {
	        				eHis = '<tr><td colspan=5>暂无数据</td></tr>';
	        			}
	        			$tbodyRegisterSetHistory.append(eHis);
	        		} 
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查询失败，请重新登录后再试');
	        	}
	        }
		});
	}

	var urlImg;
	var updateInstitutionId;
	var updateType;
	// 显示营业执照
	function loadLicenseImage( institutionId,type ){
		updateInstitutionId = institutionId
		updateType = type;
		var params = {};
		params.institutionId = institutionId;
		params.type = type;
		
		// 报告列表
		WeKnow.loading();

		$.ajax({ 
	        type: "POST", 
	        url: "invs_clinic_info.do/load_license_image", 
	        dataType: "json",
	        data: params,
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		
	        		if ( 'imagelist' in data && data.imagelist.length==0 ){
	        			WeKnow.errorMsg('图片尚未传输完成');
	        			return false;
	        		}
	        	
	        		// var $tbodyImageList = $('#tbodyImageList');
	        		// $tbodyImageList.empty();
	        		
	        		// var e = '';
	        		$(data.imagelist).each(function( idx,img){
	        			urlImg=img.originImgUrl;
	        			// e +='<tr>';
		        		// 	e +='<td>';
		        		// 		e +='<img style="width: 100%;" src="'+img.originImgUrl+'">';
		        		// 	e +='</td>';
	        			// e +='</tr>';
	        		});
	        		showImg(type,null,urlImg,null);
	        		// $tbodyImageList.append(e);
	        		//
	        		// $('#showImageModal').modal();
	        		
	        		return true;
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查询失败，请重新登录后再试');
	        	}
	        }
		});
		
		return true;
	}
	function showImg(type,picId,imgUrl,doctorId) {
		$("body").parents("html").css('overflow','hidden');
		//给body添加弹出层的html
		console.log($('.save-img'));
		var bodyHtml = "";
		bodyHtml += '<div class="mask-layer">';
		bodyHtml += '<input type="hidden" id="picId" value="'+picId+'">';
		bodyHtml += '<input type="hidden" id="type" value="'+type+'">';
		bodyHtml += '<input type="hidden" id="doctorId" value="'+doctorId+'">';
		bodyHtml += '	<div class="mask-layer-black"></div>';
		bodyHtml += '	<div class="mask-layer-container">';
		bodyHtml += '		<div class="mask-layer-container-operate">';
		bodyHtml += '			<button class="mask-out btn-default-styles">放大</button>';
		bodyHtml += '			<button class="mask-in btn-default-styles">缩小</button>';
		bodyHtml += '			<button class="mask-clockwise btn-default-styles">顺旋转</button>';
		bodyHtml += '			<button class="mask-counterclockwise btn-default-styles">逆旋转</button>';
		switch (type) {
			case "id_card":
			case "qualification":
			case "doctor_licence":
				bodyHtml += '			<button class="mask-delete btn-default-styles">删除</button>';
			case "business_licence":
			case "occupational_licence":
				bodyHtml += '			<button class="mask-edit btn-default-styles">修改</button>';
				bodyHtml += '				<input type="file" style="display:none;" id="updateImgFile">';
				break;
		}
		bodyHtml += '			<button class="mask-close btn-default-styles">关闭</button>';
		bodyHtml += ' 		</div>';
		bodyHtml += '		<div class="mask-layer-imgbox auto-img-center"></div>';
		bodyHtml += '  </div>';
		bodyHtml += '</div>';
		$("body").append(bodyHtml);

		var spin_n = 0;
		$(".mask-layer-imgbox").empty();
		spin_n = 0;
		$(".mask-layer-imgbox").append('<p><img id="showImg" src="' + imgUrl + '" alt=""></p>');

		$(".mask-layer").show();
		//图片居中显示
		var box_width = $(".auto-img-center").width(); //图片盒子宽度
		var box_height = $(".auto-img-center").height();//图片高度高度
		var initial_width = 0;//初始图片宽度
		var initial_height = 0;//初始图片高度
		var img = new Image();
		img.src = imgUrl;
		// 如果图片被缓存，则直接返回缓存数据
		if(img.complete){
			initial_width = img.width;
			initial_height = img.height;
			if (initial_width > initial_height) {
				$(".auto-img-center img").css("width", box_width);
				var last_imgHeight = $(".auto-img-center img").height();
				$(".auto-img-center img").css("margin-top", -(last_imgHeight - box_height) / 2);
			} else {
				$(".auto-img-center img").css("height", box_height);
				var last_imgWidth = $(".auto-img-center img").width();
				$(".auto-img-center img").css("margin-left", -(last_imgWidth - box_width) / 2);
			}
		}else{
			img.onload = function(){
				initial_width = img.width;
				initial_height = img.height;
				if (initial_width > initial_height) {
					$(".auto-img-center img").css("width", box_width);
					var last_imgHeight = $(".auto-img-center img").height();
					$(".auto-img-center img").css("margin-top", -(last_imgHeight - box_height) / 2);
				} else {
					$(".auto-img-center img").css("height", box_height);
					var last_imgWidth = $(".auto-img-center img").width();
					$(".auto-img-center img").css("margin-left", -(last_imgWidth - box_width) / 2);
				}
			}
		}

		//图片拖拽
		var $div_img = $(".mask-layer-imgbox p");
		//绑定鼠标左键按住事件
		$div_img.bind("mousedown", function (event) {
			event.preventDefault && event.preventDefault(); //去掉图片拖动响应
			//获取需要拖动节点的坐标
			var offset_x = $(this)[0].offsetLeft;//x坐标
			var offset_y = $(this)[0].offsetTop;//y坐标
			//获取当前鼠标的坐标
			var mouse_x = event.pageX;
			var mouse_y = event.pageY;
			//绑定拖动事件
			//由于拖动时，可能鼠标会移出元素，所以应该使用全局（document）元素
			$(".mask-layer-imgbox").bind("mousemove", function (ev) {
				// 计算鼠标移动了的位置
				var _x = ev.pageX - mouse_x;
				var _y = ev.pageY - mouse_y;
				//设置移动后的元素坐标
				var now_x = (offset_x + _x ) + "px";
				var now_y = (offset_y + _y ) + "px";
				//改变目标元素的位置
				$div_img.css({
					top: now_y,
					left: now_x
				});
			});
		});
		//当鼠标左键松开，接触事件绑定
		$(".mask-layer-imgbox").bind("mouseup", function () {
			$(this).unbind("mousemove");
		});
		//缩放 放大
		var zoom_n = 1;
		$(".mask-out").click(function () {
			zoom_n += 0.1;
			$(".mask-layer-imgbox img").css({
				"transform": "scale(" + zoom_n + ")",
				"-moz-transform": "scale(" + zoom_n + ")",
				"-ms-transform": "scale(" + zoom_n + ")",
				"-o-transform": "scale(" + zoom_n + ")",
				"-webkit-transform": "scale(" + zoom_n + ")"
			});
		});
		//缩放 缩小
		$(".mask-in").click(function () {
			zoom_n -= 0.1;
			zoom_n = zoom_n <= 0.1 ? 0.1 : zoom_n;
			$(".mask-layer-imgbox img").css({
				"transform": "scale(" + zoom_n + ")",
				"-moz-transform": "scale(" + zoom_n + ")",
				"-ms-transform": "scale(" + zoom_n + ")",
				"-o-transform": "scale(" + zoom_n + ")",
				"-webkit-transform": "scale(" + zoom_n + ")"
			});
		});
		//旋转
		$(".mask-clockwise").click(function () {
			spin_n += 90;
			$(".mask-layer-imgbox img").parent("p").css({
				"transform":"rotate("+ spin_n +"deg)",
				"-moz-transform":"rotate("+ spin_n +"deg)",
				"-ms-transform":"rotate("+ spin_n +"deg)",
				"-o-transform":"rotate("+ spin_n +"deg)",
				"-webkit-transform":"rotate("+ spin_n +"deg)"
			});
		});
		$(".mask-counterclockwise").click(function () {
			spin_n -= 90;
			$(".mask-layer-imgbox img").parent("p").css({
				"transform":"rotate("+ spin_n +"deg)",
				"-moz-transform":"rotate("+ spin_n +"deg)",
				"-ms-transform":"rotate("+ spin_n +"deg)",
				"-o-transform":"rotate("+ spin_n +"deg)",
				"-webkit-transform":"rotate("+ spin_n +"deg)"
			});
		});
		//关闭
		$(".mask-close").click(function () {
			clickShowDiv()
		});
		$(".mask-layer-black").click(function () {
			clickShowDiv()
		});
		function clickShowDiv(){
			//判断保存
			if($("#updateImgFile").val() && $("#updateImgFile").val().length > 0){
				layer.confirm('是否保存修改?', {icon: 3, title:'提示'},
					function(index){
						layer.close(index);
						updateBase64ImgByInstitutionId();
					},
					function(index){
						$("body").parents("html").css('overflow','');
						$(".mask-layer").remove();
					}
				);
			}else{
				$("body").parents("html").css('overflow','');
				$(".mask-layer").remove();
			}
		}
		$(".mask-edit").click(function () {
			$("#updateImgFile").trigger("click");
			// $(".mask-layer-imgbox").empty();
			// $(".mask-layer-imgbox").append('<form><input type="file" name=""><br>' +
			// 	'<input type="button" value="提交">' +
			// 	'</form>');
		});
		$(".mask-delete").click(function () {
			layer.confirm('是否确认删除?', {icon: 3, title:'提示'},
				function(index){
					layer.close(index);
					//删除图片获取参数
					var params = {};
					params.picId = $("#picId").val();
					params.type = $("#type").val();
					params.doctorId = $("#doctorId").val();
					params.institutionId = $("#institutionId").val();
					//删除
					$.ajax({
						type: "POST",
						url: "invs_clinic_info.do/delete_license_image_picId",
						dataType: "json",
						data: params,
						async: true,//异步调用
						success: function(data) {
							$("body").parents("html").css('overflow','');
							$(".mask-layer").remove();
							WeKnow.closeLoading();
							if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
							if (data.errcode == 0) {
								//清除图片标
								$("td.show_img img[data-pic-id='"+params.picId+"']").remove();
								WeKnow.successMsg('删除成功');
								return true;
							} else if (data.errcode == -1 ) {
								WeKnow.errorMsg( data.errMsg );
							} else {
								WeKnow.systemMsg('编辑失败，请重新登录后再试');
							}
						}
					});
				},
				function(index){
					$("body").parents("html").css('overflow','');
					$(".mask-layer").remove();
				}
			);
		});


		$("#updateImgFile").change(function (e) {
			var file = e.target.files[0];
			var reader = new FileReader();
			reader.readAsDataURL(file); //读出 base64
			reader.onloadend = function () {
				// 图片的base64值
				var base64 = "data:image/png;base64," + reader.result.substring(reader.result.indexOf(",")+1);
				$("#showImg").attr("src", base64);
			};
		});

		function updateBase64ImgByInstitutionId(){
			var type = $("#type").val();
			if(type == "business_licence" || type == "occupational_licence"){
				//修改原字段内容
				var params = {};
				params.institutionId = updateInstitutionId;
				params.type = type;
				params.base64 = $("#showImg").attr("src");
				//修改
				$.ajax({
					type: "POST",
					url: "invs_clinic_info.do/update_license_image",
					dataType: "json",
					data: params,
					async: true,//异步调用
					success: function(data) {
						$("body").parents("html").css('overflow','');
						$(".mask-layer").remove();
						WeKnow.closeLoading();
						if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
						if (data.errcode == 0) {
							return true;
						} else if (data.errcode == -1 ) {
							WeKnow.errorMsg( data.errMsg );
						} else {
							WeKnow.systemMsg('编辑失败，请重新登录后再试');
						}
					}
				});
			}else if(type == "id_card" || type == "qualification" || type == "doctor_licence"){
				//修改图片表内容
				var params = {};
				params.picId = $("#picId").val();
				params.type = type;
				params.base64 = $("#showImg").attr("src");
				//修改
				$.ajax({
					type: "POST",
					url: "invs_clinic_info.do/update_license_image_picId",
					dataType: "json",
					data: params,
					async: true,//异步调用
					success: function(data) {
						$("body").parents("html").css('overflow','');
						$(".mask-layer").remove();
						WeKnow.closeLoading();
						if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
						if (data.errcode == 0) {
							return true;
						} else if (data.errcode == -1 ) {
							WeKnow.errorMsg( data.errMsg );
						} else {
							WeKnow.systemMsg('编辑失败，请重新登录后再试');
						}
					}
				});
			}
		}
	}
	// 显示营业执照
	function downloadLicenseImage( institutionId,institutionName,type ){
		
		var params = {};
		params.institutionId = institutionId;
		params.institutionName = institutionName;
		params.type = type;
		
		// 报告列表
		WeKnow.loading();

		var url = 'invs_clinic_info.do/download';
    	
    	WeKnow.loading();
    	$.fileDownload(url,
    		{
            httpMethod: 'POST',
            data: params,
            prepareCallback:function(url){
            	console.log('download start')
            	WeKnow.loading();
            },
            successCallback:function(url){
            	console.log('download end')
            	WeKnow.closeLoading();
            },
            failCallback: function (html, url) {
            	WeKnow.errorMsg('图片尚未上传');
				WeKnow.closeLoading();
            }
         });
		
		return true;
	}
	
	
	// 显示医生信息
	function loadDoctors(institutionId){
		
		var params = {};
		
		params.institutionId=institutionId;
		var doctorName = $.trim($('#doctot_register_info').find('input[name="doctorName"]').val());
		if ( doctorName != '' ){
			params.doctorName = doctorName;
		}
		
		var $tbodyRegisterInfoDetailList = $('tbody#tbodyRegisterInfoDetailList');
		$tbodyRegisterInfoDetailList.empty();
		
		WeKnow.loading();
		
		$.ajax({ 
	        type: "POST", 
	        url: "invs_doctor_verify.do/load_list", 
	        dataType: "json",
	        data: params,
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		
	        		if ( 'datalist' in data && data.datalist.length == 0 ){
	        			WeKnow.errorMsg('没有查询到医生数据');
	        			return;
	        		}
	        		
	        		// 把取到的结果放到
	        		var e = '';
	        		var titleList = data.titleList;//职称
	        		var scopePracticeList = data.scopePracticeList;// 执业范围
					var antibiosisList = data.antibiosisList;// 抗菌药物标记
	        		
	        		var hasList = [];
	        		hasList.push({value:0,fullName:'无'});
	        		hasList.push({value:1,fullName:'有'});
	        		
	        		$(data.datalist).each(function( idx,_a){
	        			e+='<tr class="pointer" ';
		        				e+= ' data-doctor_id="' + _a.doctor.id + '"';
	        			e+='>';
		        			// 医师姓名
		        			e+='<td class="text-center">';
	        				    var phone = ( _a.doctor.phone == null?'':_a.doctor.phone );
	        				    e+='<span name="name" class="doctor-modify-togle">'+ _a.doctor.name +'</span>';
	        					e+= '<input style="display:none;"  type="text" name="name" class="form-control doctor-modify-togle" value="' + _a.doctor.name + '"/>'
	        				e+= '</td>';
	        				// 电话
	        				e+='<td class="text-center">';
	        				    var phone = ( _a.doctor.phone == null?'':_a.doctor.phone );
	        				    e+='<span name="phone" class="doctor-modify-togle">'+phone +'</span>';
	        					e+= '<input style="display:none;"  type="text" name="phone" class="form-control doctor-modify-togle" value="' + phone + '"/>'
	        				e+= '</td>';
		        			// 职称
	        				e+='<td class="text-center">';
	        				    var technicalTitleName = ( _a.technicalTitleName == null?'':_a.technicalTitleName );
	        				    e+='<span name="technicalTitleName" class="doctor-modify-togle">'+technicalTitleName +'</span>';
	        				    e+='<select style="display:none;"  class="form-control doctor-modify-togle" name="technicalTitle">';
	        				    	e +='<option value="-1">请选择</option>"';
	        				        $( titleList ).each( function(idx,a){
	        				        	e +='<option value="'+ a.value + '"'+ ( a.value ==_a.doctor.technicalTitle ? 'selected="selected"':'')+'>'+ a.fullName + '</option>';
	        				        });
								e+='</select>';
	        				e+= '</td>';
		        			// 执业范围
	        				e+='<td class="text-center">';
	        					var scopePracticeName = ( _a.scopePracticeName == null?'':_a.scopePracticeName );
	        				    e+='<span name="scopePracticeName" class="doctor-modify-togle">'+scopePracticeName +'</span>';
	        				    e+='<select style="display:none;"  class="form-control doctor-modify-togle" name="scopePractice">';
	        				    	e +='<option value="-1">请选择</option>"';
	        				        $( scopePracticeList ).each( function(idx,a){
	        				        	e +='<option value="'+ a.value + '"'+ ( a.value ==_a.doctor.scopePractice ? 'selected="selected"':'')+'>'+ a.fullName + '</option>';
	        				        });
								e+='</select>';
							e+= '</td>';
	        				// 身份证号
	        				e+='<td class="text-center">';
	        					var idCard = ( _a.doctor.idCard == null?'':_a.doctor.idCard );
	        					e+='<span name="idCard" class="doctor-modify-togle">'+ idCard +'</span>';
	        					e+= '<input style="display:none;"  type="text" name="idCard" class="form-control doctor-modify-togle" value="' + idCard + '"/>'
	        				e+='</td>';
	        				// 抗菌药物 处方权
	        				e+='<td class="text-center">';
	        					var antibiosisAuthorityName = ( _a.antibiosisAuthorityName == null?'':_a.antibiosisAuthorityName );
	        				    e+='<span name="antibiosisAuthorityName" class="doctor-modify-togle">'+antibiosisAuthorityName +'</span>';
	        				    e+='<select style="display:none;"  class="form-control doctor-modify-togle" name="antibiosisAuthority">';
	        				        $( antibiosisList ).each( function(idx,a){
	        				        	e +='<option value="'+ a.value + '"'+ ( a.value ==_a.doctor.antibiosisAuthority ? 'selected="selected"':'')+'>'+ a.abbreviation + '</option>';
	        				        });
								e+='</select>';
							e+= '</td>';
	        				
	        				// 麻醉药品第一类精神药品处方资格
	        				e+='<td class="text-center">';
	        					var anestheticAuthorityName = ( _a.doctor.anestheticAuthority == 1?'有':'无');
	        				    e+='<span name="anestheticAuthorityName" class="doctor-modify-togle">'+anestheticAuthorityName +'</span>';
	        				    e+='<select style="display:none;"  class="form-control doctor-modify-togle" name="anestheticAuthority">';
	        				        $( hasList ).each( function(idx,a){
	        				        	e +='<option value="'+ a.value + '"'+ ( a.value ==_a.doctor.anestheticAuthority ? 'selected="selected"':'')+'>'+ a.fullName + '</option>';
	        				        });
								e+='</select>';
							e+= '</td>';
	        				// 身份证 图片
							e+='<td data-type="id_card" class="text-center show_img" name="id_card_show">';
	        				if (_a.doctor.idCardAtta != null){
	        					var idCardAttaList = _a.doctor.idCardAtta.split(',');
								for(var index in idCardAttaList){
									if(idCardAttaList[index].length > 0){
										e+='<img style="width: 25px;margin-left: 2px;" src="img/photo.png" ' +
											'data-type="id_card" data-pic-id="'+idCardAttaList[index]+'">';
									}
								}
	        				}
							e+='</td>';
		        			// 医师资格证书
							e+='<td data-type="qualification" class="text-center show_img" name="qualification_show">';
	        				if (_a.doctor.qualificationAtta != null){
	        					var qualificationAttaList = _a.doctor.qualificationAtta.split(',');
								for(var index in qualificationAttaList){
									if(qualificationAttaList[index].length > 0){
										e+='<img style="width: 25px;margin-left: 2px;" src="img/photo.png" ' +
											'data-type="qualification" data-pic-id="'+qualificationAttaList[index]+'">';
									}
								}
	        				}
							e+='</td>';
	        				// 医师执业证书
							e+='<td data-type="doctor_licence" class="text-center show_img" name="doctor_licence_show">';
	        				if (_a.doctor.doctorLicenceAtta != null){
	        					var doctorLicenceAttaList = _a.doctor.doctorLicenceAtta.split(',');
								for(var index in doctorLicenceAttaList){
									if(doctorLicenceAttaList[index].length > 0){
										e+='<img style="width: 25px;margin-left: 2px;" src="img/photo.png" ' +
											'data-type="doctor_licence" data-pic-id="'+doctorLicenceAttaList[index]+'">';
									}
								}
	        				}
							e+='</td>';
	        				// 操作
	        				e+='<td class="text-center">';
	        					e+='<button type="button" name="modify" class="btn btn-primary btn-sm doctor-modify-togle">修改</button>';
	        					e+='<button type="button" name="save" style="display:none;" class="btn btn-primary btn-sm doctor-modify-togle save-img">保存</button>';
	        				e+='</td>'
	        			e+='</tr>';
	        		});
	        		$tbodyRegisterInfoDetailList.append(e);
	        		
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查询失败，请重新登录后再试');
	        	}
	        }
		});
	}	
	
	// 显示医生相关图图片
	function loadImage( institutionId,doctorId,type,picId){
		
		var params = {};
		// 输入有误的情况下，退出
		params.institutionId = institutionId;
		params.doctorId = doctorId;
		params.type = type;
		params.picId = picId;

		// 报告列表
		WeKnow.loading();

		$.ajax({ 
	        type: "POST", 
	        url: "invs_clinic_info.do/load_image_picId",
	        dataType: "json",
	        data: params,
	        async: true,//异步调用
	        success: function(data) {
	        	
	        	WeKnow.closeLoading();
	        	
				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
	        	
	        	if (data.errcode == 0) {
	        		if ( 'imagelist' in data && (!data.imagelist || !data.imagelist.length) ){
	        			WeKnow.errorMsg('图片尚未传输完成');
	        			return false;
	        		}

	        		var $tbodyImageList = $('#tbodyImageList');
	        		$tbodyImageList.empty();

	        		//未变更修改状态，不可编辑
	        		if($('.save-img').css("display")=='none'){
	        			type = "";
					}
	        		$(data.imagelist).each(function( idx,img){
						showImg(type,picId,img.originImgUrl,doctorId);
	        		});
	        		return true;
	        	} else if (data.errcode == -1 ) {
	        		WeKnow.errorMsg( data.errMsg );
	        	} else {
	        		WeKnow.systemMsg('查询失败，请重新登录后再试');
	        	}
	        }
		});
		return true;
	}
	
	// 输入校验、并返回更新用entity
	function checkInput( saveBtn ){
		
		var $parent = saveBtn.closest('tr');
		// 医师姓名
		var $name =  $parent.find('input[name="name"]');
		if ( !$.trim($name.val()).length ){
			 WeKnow.errorMsg('请输入医生姓名');
			 $name.focus();
			 return false;
		}
		// 电话
		var $phone =  $parent.find('input[name="phone"]');
		if ( !$.trim($phone.val()).length ){
			 WeKnow.errorMsg('请输入电话');
			 $phone.focus();
			 return false;
		}
		
		var $technicalTitle = $parent.find('select[name="technicalTitle"]');// 职称
		if ( $technicalTitle.val() == '-1' ){
			WeKnow.errorMsg('请选择职称');
			$technicalTitle.focus();
			return false;	
		}
		
		var $scopePractice = $parent.find('select[name="scopePractice"]');// 执业范围
		if ( $scopePractice.val() == '-1' ){
			WeKnow.errorMsg('请选择执业范围');
			$scopePractice.focus();
			return false;	
		}
		
		// 身份证号
		var $idCard = $parent.find('input[name="idCard"]');
		if ( !$idCard.val().length) {
			 WeKnow.errorMsg('请输入身份证号码');
			 $idCard.focus();
			 return false;
		}
		
		if (!IDCARD_UTIL.IdCardValidate($idCard.val())) {
			WeKnow.errorMsg('身份证号码不正确');
			$idCard.focus();
			return false;
		}
		
		// 返回值
		var params = {};
		params.id = $parent.data('doctor_id');
		params.institutionId = $("#institutionId").val();
		params.name = $name.val();
		params.phone = $phone.val();
		params.idCard = $idCard.val();
		params.technicalTitle = $technicalTitle.val();
		params.scopePractice = $scopePractice.val();
		params.antibiosisAuthority = $parent.find('select[name="antibiosisAuthority"]').val();// 抗菌药处方权
		params.anestheticAuthority = $parent.find('select[name="anestheticAuthority"]').val();// 精麻药处方权
		
		return params;
	}
	function saveInstitutionType() {
		var params = {};
		params.id = $('#editInstitutionInfo .edit-institution-id').val();
		params.institutionType = $('#editInstitutionInfo #institutionType').val();
		WeKnow.loading();
		$.ajax({
			type: "POST",
			url: "invs_clinic_info.do/save_institutionType",
			dataType: "json",
			data: JSON.stringify(params),
			contentType: "application/json;charset=utf-8",
			async: false,//异步调用
			success: function(data) {
				WeKnow.closeLoading();

				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

				if (data.errcode == 0) {
					WeKnow.successMsg('更新成功');
					$('#editInstitutionInfo').modal('hide');
					// 页面初期数据刷新
					MY_CLINIC_INFO.loadInstitutions();

				} else if (data.errcode == -1 ) {
					WeKnow.errorMsg( data.errMsg );
				} else {
					WeKnow.systemMsg('更新失败，请重新登录后再试');
				}
			}
		});
	}

	function saveInstitutionTypeLink() {
		var params = {};
		params.id = $('#editInstitutionInfoLink .edit-institution-id').val();
		params.institutionAttr = $('#editInstitutionInfoLink #institutionAttr').val();
		params.institutionTypeFirst = $('#editInstitutionInfoLink #institutionTypeFirst').val();
		params.institutionTypeSecond = $('#editInstitutionInfoLink #institutionTypeSecond').val();
        params.town = $('#editInstitutionInfoLink #townSelect').val();
		WeKnow.loading();
		$.ajax({
			type: "POST",
			url: "invs_clinic_info.do/save_institutionType",
			dataType: "json",
			data: JSON.stringify(params),
			contentType: "application/json;charset=utf-8",
			async: false,//异步调用
			success: function(data) {
				WeKnow.closeLoading();

				if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

				if (data.errcode == 0) {
					WeKnow.successMsg('更新成功');
					$('#editInstitutionInfoLink').modal('hide');
					// 页面初期数据刷新
					MY_CLINIC_INFO.loadInstitutions();

				} else if (data.errcode == -1 ) {
					WeKnow.errorMsg( data.errMsg );
				} else {
					WeKnow.systemMsg('更新失败，请重新登录后再试');
				}
			}
		});
	}

	return {
		loadInstitutions:loadInstitutions,
		loadLicenseImage:loadLicenseImage,
		downloadLicenseImage:downloadLicenseImage,
		loadDoctors:loadDoctors,
		loadImage:loadImage,
		checkInput:checkInput,
		loadInstitutionRegisterSetInfo:loadInstitutionRegisterSetInfo,
		saveInstitutionType:saveInstitutionType,
		saveInstitutionTypeLink:saveInstitutionTypeLink,
        showImg:showImg
	}
})();

$(document).ready(function() {
	
	// 页面初期数据查询
	MY_CLINIC_INFO.loadInstitutions();
	
	//查询按钮按下
	$('#search').on('click',function(){
		MY_CLINIC_INFO.loadInstitutions();
	});
	// 查看记录
//	$('#tbodyInstitutionList').on('click','button[name="showDetail"]',function(){
//		var $that = $(this);
//		var $parentTr = $that.closest('tr');
//		
//		$('.toggle-input').toggle();//主页面·详细页面切换显示
//		//记住选中的机构Id
//		var institutionId = $parentTr.data('institution_id');
//		$('#institutionId').val(institutionId);
//		// 显示选中的机构名
//		var institutionName = $parentTr.data('institution_name');
//		$('#institution_name_dis').text(institutionName);
//		// 第一个tab显示
//		$('.div_tab_panel :first').click();
//	});
	
	// 备案信息  
//	$('#tbodyInstitutionList').on('click','button[name="archival"]',function(){
//		var $that = $(this);
//		var $parentTr = $that.closest('tr');
//		
//		$('.toggle_doctot_register_info').toggle();//主页面·备案信息页面切换显示
//		//记住选中的机构Id
//		var institutionId = $parentTr.data('institution_id');
//		$('#institutionId').val(institutionId);
//		// 显示选中的机构名
//		var institutionName = $parentTr.data('institution_name');
//		$('#institution_name_register_dis').text(institutionName);
//		// 查询诊所对应的医生
//		MY_CLINIC_INFO.loadDoctors(institutionId);
//	});
	
	// 回退
	$('i.backToWorkspace').on('click',function(){
		$('section').hide();//主页面·详细页面切换显示
		// 清空一下医生名字查询条件
		$('input[name="doctorName"]').val('');
		// 显示主页面
		$('section#main_page').show();
	});
	//主页面·备案页面切换显示
	$('#backToWorkspaceDoctor').on('click',function(){
		// 页面显示
		$('.toggle_doctot_register_info').toggle();
		// 清空一下医生名字查询条件
		$('input[name="doctorName"]').val('');
	});
	
	// 功能按钮按下
	$('#tbodyInstitutionList').on("click", 'ul a', function(e) {
		var $that = $(this);

		var actionName = $that.prop('name');
		
		var $parentTr = $that.closest('tr');
		
		var institutionId = $parentTr.data('institution_id');
		var institutionName = $parentTr.data('institution_name');
		var institutionType = $parentTr.data('institution_type');
		var institutionTypeFirst = $parentTr.data('institution_type_first');
		var institutionTypeSecond = $parentTr.data('institution_type_second');
		var institutionAttr = $parentTr.data('institution_attr');
        var town = $parentTr.data('town');

		var params = {};
		
		if ( actionName == 'archival' ){
			$('section').css('display','none');//所有section隐藏
			
			//记住选中的机构Id
			$('#institutionId').val(institutionId);
			// 显示选中的机构名
			$('#institution_name_register_dis').text(institutionName);
			// 查询诊所对应的医生
			MY_CLINIC_INFO.loadDoctors(institutionId);
			
			$('section#doctot_register_info').show();
			
			return;// 退出处理
		} else if ( actionName == 'invs_set' ){ //监管规则
			$('section').css('display','none');//所有section隐藏
			// 显示规则修改历史
			MY_CLINIC_INFO.loadInstitutionRegisterSetInfo(institutionId);
			
			$('section#registerSetHistory').find('span.institution_name_register_dis').text(institutionName);
			$('section#registerSetHistory').show();

			return;// 退出处理
			
		} else if (actionName == 'institution_type') {	//修改机构类型
			$('#editInstitutionInfo #insName').html(institutionName);
			$('select#institutionType').find("option[value="+institutionType+"]").prop("selected",true);
			$('#editInstitutionInfo .edit-institution-id').val(institutionId);
			$('#editInstitutionInfo').modal('show');

			return;
		} else if (actionName == 'institution_type_link') {	//修改机构类型目录
			$('#editInstitutionInfoLink #insNameLink').html(institutionName);
			//机构属性
            if(institutionAttr) {
                $('select#institutionAttr').find("option[value=" + institutionAttr + "]").prop("selected", true);
            }
			//展示一级分类
            if(institutionTypeFirst){
                $('select#institutionTypeFirst').find("option[value="+institutionTypeFirst+"]").prop("selected",true);
                //隐藏不属于一级分类的二级分类
                if(institutionTypeSecond){
                    hideNotSecond();
                    $('select#institutionTypeSecond').find("option[value="+institutionTypeSecond+"]").prop("selected",true);
                }
            }
            //展示乡镇/街道
            if(town){
                $('select#townSelect').find("option[value="+town+"]").prop("selected",true);
            }
			$('#editInstitutionInfoLink .edit-institution-id').val(institutionId);
			$('#editInstitutionInfoLink').modal('show');

			return;
		} else if ( actionName == 'closeSupervise'  ){// 关闭监管
			params.underInvs = 0;
		} else if ( actionName == 'openSupervise' ){// 关闭监管
			params.underInvs = 1;
		} else if ( actionName == 'closePrescriptionSupervise'  ){// 关闭处方监管
			params.prescriptionInvs = 0;
		} else if ( actionName == 'openPrescriptionSupervise' ){// 打开处方监管
			params.prescriptionInvs = 1;
		}
		
		params.institutionId = institutionId;
		// 保存对话框
		WeKnow.confirm('是否保存修改？',function(){
			$.ajax({ 
		        type: "POST", 
		        url: "invs_clinic_info.do/save_institution",
		        dataType: "json",
		        data: params,
		        async: true,//异步调用
		        success: function(data) {
		        	WeKnow.closeLoading();
		        	
					if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
		        	
		        	if (data.errcode == 0) {
		        		WeKnow.successMsg('更新成功');
		        		// 页面初期数据刷新
		        		MY_CLINIC_INFO.loadInstitutions();
		        		
		        	} else if (data.errcode == -1 ) {
		        		WeKnow.errorMsg( data.errMsg );
		        	} else {
		        		WeKnow.systemMsg('更新失败，请重新登录后再试');
		        	}
		        }
			});
		});
	});

	//隐藏不属于当前的二级类别
	function hideNotSecond(){
		//获取当前一级类别
		var firstVal = $('select#institutionTypeFirst').val();
		//隐藏全部二级类型
		$('select#institutionTypeSecond option').hide();
		//显示一级类别所属的二级类别
		$('select#institutionTypeSecond .first_'+firstVal).show();
		//默认选中第一个
		$('select#institutionTypeSecond .first_'+firstVal+':first').prop("selected",true);
	}

	//一级联动类别下拉变更
	$("#institutionTypeFirst").change(function (e) {
		hideNotSecond();
	});

	// 显示营业执照图片
	$('#tbodyInstitutionList').on('click','button[name="showImage"]',function(){
		var $that = $(this)
		var $parent = $that.closest('tr');
		$('#imageModalTitle').text($that.data('institution_name'));
		var institutionId = $parent.data('institution_id');
		var type = $that.closest('td').data('type');
		MY_CLINIC_INFO.loadLicenseImage(institutionId,type);
	});
	
	// 文件下载
	$('#tbodyInstitutionList').on('click','button[name="download"]',function(){
		var $that = $(this);
		var $parent = $that.closest('tr');
    	
    	var institutionId = $parent.data('institution_id');
    	var institutionName = $parent.data('institution_name');
		var type = $that.closest('td').data('type');
    	MY_CLINIC_INFO.downloadLicenseImage(institutionId,institutionName,type);
	});
	
	// 显示医生照片
	$('tbody#tbodyRegisterInfoDetailList').on('click','td.show_img img',function(){
		var $that = $(this);
		
		var institutionId = $('#institutionId').val();
		var doctorId = $that.closest('tr').data('doctor_id');
		var type = $that.data('type');
		var picId = $that.data('pic-id');
		if(picId){
			MY_CLINIC_INFO.loadImage(institutionId,doctorId,type,picId);//显示图片
		}else{
			//新增图片
			addImg.institutionId = institutionId;
			addImg.doctorId = doctorId;
			addImg.type = type;
			addImgThat = $that;
			$("#tempFile").val("");
			$("#tempFile").trigger("click");
		}
	});

	var addImg = {};
	var addImgThat;

	$("#tempFile").change(function (e) {
		var file = e.target.files[0];
		var reader = new FileReader();
		reader.readAsDataURL(file); //读出 base64
		reader.onloadend = function () {
			// 图片的base64值
			var base64 = "data:image/png;base64," + reader.result.substring(reader.result.indexOf(",")+1);
			addImg.base64 = base64;
			//保存
            $.ajax({
                type: "POST",
                url: "invs_clinic_info.do/save_pic",
                dataType: "json",
                data: addImg,
                async: true,//异步调用
                success: function(data) {
                    WeKnow.closeLoading();
                    if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
                    if (data.errcode == 0) {
                        WeKnow.successMsg('添加成功');
                        //显示图片
                        //MY_CLINIC_INFO.showImg(addImg.type + "add", data.picId, addImg.base64);
                        //添加图片图标
						var idCardHtml = '<img class="tempImg" data-type="'+addImg.type+'" data-pic-id="'+data.picId+'" style="width: 25px;margin-left: 2px;" src="img/photo.png">';
						addImgThat.closest('tr').find('.show_img[name="'+addImg.type+'_show"] .tempImg').before(idCardHtml);
                    } else if (data.errcode == -1 ) {
                        WeKnow.errorMsg( data.errMsg );
                    } else {
                        WeKnow.systemMsg('添加失败，请重新登录后再试');
                    }
                }
            });
		};
	});

	// $('input[name="underInvs"]').on('change',function(){
	// 	MY_CLINIC_INFO.loadInstitutions();
	// });
	$('select[name="underInvs"]').on('change',function(){
		if ($('select[name="underInvs"]').val() == 0) {
			$('select[name="prescriptionInvs"]').val(9);
			$('select[name="prescriptionInvs"]').attr("disabled","disabled");
		} else {
			//$('select[name="prescriptionInvs"]').attr("selected",false);
			$('select[name="prescriptionInvs"]').removeAttr("disabled");
		}
		MY_CLINIC_INFO.loadInstitutions();
	});
	$('select[name="prescriptionInvs"]').on('change',function(){
		MY_CLINIC_INFO.loadInstitutions();
	});
	$('select[name="occupationalLicenceStatus"]').on('change',function(){
		MY_CLINIC_INFO.loadInstitutions();
	});
	$('select[name="institutionTypeFirstScreen"]').on('change',function(){
		MY_CLINIC_INFO.loadInstitutions();
	});

	//筛选一级类目变更
    $('select[name="institutionTypeFirstScreen"]').on('change',function(){
       //直接查询


    });

	
	// 修改医生注册信息
	$('#tbodyRegisterInfoDetailList').on('click','button[name="modify"]',function(){
		var $that = $(this)
		// 该行变为修改模式
		$that.closest('tr').find('.doctor-modify-togle').toggle();
		//添加新增图片按钮
		var idCardHtml = '<img class="tempImg" data-type="id_card" style="width: 25px;margin-left: 2px;" src="img/add.png">';
		$that.closest('tr').find('.show_img[name="id_card_show"]').append(idCardHtml);
		var qualificationHtml = '<img class="tempImg" data-type="qualification" style="width: 25px;margin-left: 2px;" src="img/add.png">';
		$that.closest('tr').find('.show_img[name="qualification_show"]').append(qualificationHtml);
		var doctorLicenceHtml = '<img class="tempImg" data-type="doctor_licence" style="width: 25px;margin-left: 2px;" src="img/add.png">';
		$that.closest('tr').find('.show_img[name="doctor_licence_show"]').append(doctorLicenceHtml);
	});


	// 查询
	$('button[name="searchDoctor"]').on('click',function(){
		MY_CLINIC_INFO.loadDoctors($('#institutionId').val());
	});
	
	// 修改医生注册信息
	$('#tbodyRegisterInfoDetailList').on('click','button[name="save"]',function(){
		
		var $that = $(this);
		
		var params = MY_CLINIC_INFO.checkInput( $that );
		// 输入检验失败时
		if (!params){
			return;
		}
		// 保存对话框
		WeKnow.confirm('是否保存修改？',function(){
			$.ajax({
		        type: "POST", 
		        url: "invs_clinic_info.do/save_doctor", 
		        dataType: "json",
		        contentType:"application/json",
		        data: JSON.stringify(params),
		        async: true,//异步调用
		        success: function(data) {
		        	
		        	WeKnow.closeLoading();
		        	
					if (!WeKnow.filterAjaxResult(data)) return false; // session过期check
		        	
		        	if (data.errcode == 0) {
		        		
		        		/*
		        		// 该行变为显示模式
		        		var $parantTr = $that.closest('tr');
		        		// 把值写回页面
		        		$parantTr.find('span[name="name"]').text(params.name); 
		        		$parantTr.find('span[name="phone"]').text(params.phone);
		        		$parantTr.find('span[name="idCard"]').text(params.idCard);
		        		var technicalTitleName = $parantTr.find('select[name="technicalTitle"] option:selected').text();// 职称
		        		$parantTr.find('span[name="technicalTitleName"]').text(technicalTitleName);
		        		// 执业范围
		        		var scopePracticeName = $parantTr.find('select[name="scopePractice"] option:selected').text();
		        		$parantTr.find('span[name="scopePracticeName"]').text(scopePracticeName);
		        		
		        		var antibiosisAuthorityName = $parantTr.find('select[name="antibiosisAuthority"] option:selected').text();// 抗菌药处方权
		        		$parantTr.find('span[name="antibiosisAuthority"]').text(antibiosisAuthorityName);
		        		// 精麻药处方权
		        		var anestheticAuthorityName = $parantTr.find('select[name="anestheticAuthority"] option:selected').text();
		        		$parantTr.find('span[name="anestheticAuthority"]').text(anestheticAuthorityName);// 精麻药处方权
		        		
		        		$parantTr.find('.doctor-modify-togle').toggle();
		        		*/
		        		
		        		MY_CLINIC_INFO.loadDoctors($('#institutionId').val());
		        		
		        		WeKnow.successMsg('医生信息更新成功');
		        	} else if (data.errcode == -1 ) {
		        		WeKnow.errorMsg( data.errMsg );
		        	} else {
		        		WeKnow.systemMsg('更新失败，请重新登录后再试');
		        	}
		        }
			});
		});
	});

	//修改机构类型保存按钮按下
	$('#editInstitutionInfo #save').on('click',function(){
		MY_CLINIC_INFO.saveInstitutionType();
	});

	//修改机构类型联动保存按钮按下
	$('#editInstitutionInfoLink #saveLink').on('click',function(){
		MY_CLINIC_INFO.saveInstitutionTypeLink();
	});

});